package com.ler.auth.filter;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.ler.yrmall.dto.LoginUser;
import com.ler.yrmall.constant.YuruoConstant;
import com.ler.yrmall.dto.UserDTO;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author Leron
 */
@Activate(group = {CommonConstants.PROVIDER}, order = Integer.MAX_VALUE)
public class UserDubboProviderFilter implements Filter {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String userInfo = invocation.getAttachment(YuruoConstant.USER_HEADER);
        if (userInfo != null) {
            LoginUser user = JSON.parseObject(userInfo, LoginUser.class);
            UserDTO userDTO = BeanUtil.copyProperties(user,UserDTO.class);
            UsernamePasswordAuthenticationToken credentials = new UsernamePasswordAuthenticationToken(userDTO,null, AuthorityUtils.createAuthorityList());
            SecurityContextHolder.getContext().setAuthentication(credentials);
        }
        return invoker.invoke(invocation);
    }
}
